package future;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;

/**
 * @author 黄乾坤
 * @create 2023-09-15 18:12
 */
public class CompleteAsync {

    public static void main(String[] args) throws TimeoutException {

        List<Integer> list = new ArrayList<>();
        CompletableFuture<Integer> one = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            throw new RuntimeException("运行时异常");
//            return 1;
        });

        CompletableFuture<Integer> two = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            throw new RuntimeException("运行时异常");
            return 2;
        });

        CompletableFuture<Integer> three = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 3;
        });

        try {
            Void unused1 = CompletableFuture.allOf(one, two, three).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        Throwable join = CompletableFuture.allOf(one, two, three)
                                          .handle((unused, throwable) -> {

                                              if(throwable != null) {
                                                  System.out.println(throwable);

                                                  return throwable.getCause();
                                              }

                                              throw  new RuntimeException("222222");

                                          })
                                          .join();

        if(join instanceof RuntimeException) {
            throw (RuntimeException)join;
        }

        System.out.println(join.getCause());
        System.out.println("55555555555555555");
        System.out.println(list);

    }
}
